package com.zzzzzz.sys.menu;

import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zzzzzz.plugins.shiro.I;

@Service
public class MenuService {
	@Resource
	public MenuDao menuDao;

	@Transactional
	public int save(Menu menu, I i) {
		menu.setUpdDt(new Date());
		menu.setUpdBy(i.getId());
		if (menu.getId() == null) {
			menu.setAddDt(new Date());
			menu.setAddBy(i.getId());
			menuDao.add(menu);
		} else {
			menuDao.updById(menu);
		}

		return 1;
	}

	public List<ZTree> findListById(Long id) {
		List<ZTree> zTreeList = new LinkedList<ZTree>();
		List<ZTree> list;
		if (id == null) {
			list = menuDao.findListByNullPid();
		} else {
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("pid", id);
			list = menuDao.findListByPid(params);
		}

		if (CollectionUtils.isEmpty(list)) {
			return null;
		}
		for (ZTree zTree : list) {
			zTreeList.add(addLeafMenu(zTree));
		}
		return zTreeList;
	}

	private ZTree addLeafMenu(ZTree zTree) {
		if (zTree == null) {
			return null;
		}
		Long id = zTree.getId();
		if (id == null) {
			return null;
		}

		List<ZTree> list = findListById(id);
		if (CollectionUtils.isEmpty(list)) {
			return zTree;
		}
		zTree.setChildren(list);
		return zTree;
	}
}
